//go:build windows
// +build windows

package gui

import (
	"encoding/base64"
	"fmt"
	"mcp-clarification-service/internal/config"
	"mcp-clarification-service/internal/tools"
	"os/exec"
	"strings"
	"sync"
	"time"
)

// NativeManager 使用Windows原生对话框的管理器
type NativeManager struct {
	config *config.GUIConfig
	mu     sync.Mutex
	active bool
}

// NewNativeManager 创建原生管理器
func NewNativeManager(cfg *config.GUIConfig) *NativeManager {
	return &NativeManager{
		config: cfg,
	}
}

// ShowQuestions 显示问题（使用PowerShell GUI）
func (m *NativeManager) ShowQuestions(questions []tools.Question, timeout time.Duration) ([]tools.Answer, bool, error) {
	m.mu.Lock()
	if m.active {
		m.mu.Unlock()
		return nil, false, fmt.Errorf("another window is active")
	}
	m.active = true
	m.mu.Unlock()

	defer func() {
		m.mu.Lock()
		m.active = false
		m.mu.Unlock()
	}()

	// 如果只有一个问题，提供循环确认流程
	if len(questions) == 1 {
		q := questions[0]
		var previous *tools.Answer

		for {
			var (
				answer    tools.Answer
				cancelled bool
				err       error
			)

			switch q.Type {
			case "single":
				answer, cancelled, err = m.showSingleChoice(q, previous)
			case "multiple":
				answer, cancelled, err = m.showMultipleChoice(q, previous)
			case "free_text":
				answer, cancelled, err = m.showFreeText(q, previous)
			default:
				return nil, false, fmt.Errorf("unknown question type: %s", q.Type)
			}

			if err != nil {
				return nil, false, err
			}
			if cancelled {
				return nil, true, nil
			}

			confirmed, err := m.confirmAnswersNative([]tools.Question{q}, []tools.Answer{answer})
			if err != nil {
				return nil, false, err
			}

			if confirmed {
				return []tools.Answer{answer}, false, nil
			}

			// 用户选择返回修改，保留当前答案用于下一轮默认值
			previous = &answer
		}
	}

	var previous []tools.Answer
	for {
		answers, cancelled, err := m.showMultipleQuestions(questions, timeout, previous)
		if err != nil {
			return nil, false, err
		}
		if cancelled {
			return nil, true, nil
		}

		confirmed, err := m.confirmAnswersNative(questions, answers)
		if err != nil {
			return nil, false, err
		}
		if confirmed {
			return answers, false, nil
		}

		previous = answers
	}
}

// showSingleChoice 显示单选对话框（优化版：使用RadioButton）
func (m *NativeManager) showSingleChoice(q tools.Question, previous *tools.Answer) (tools.Answer, bool, error) {
	// 计算窗口高度：基础高度 + 每个选项的高度 + "其他"选项高度 + 按钮面板高度 + 额外空间
	optionHeight := 30
	baseHeight := 200
	buttonPanelHeight := 80 // 增加按钮面板高度
	otherOptionHeight := 40 // "其他"选项 + 输入框的高度
	extraSpace := 50        // 额外空间确保按钮可见
	clientHeight := baseHeight + len(q.Options)*optionHeight + otherOptionHeight + buttonPanelHeight + extraSpace
	if clientHeight > 750 {
		clientHeight = 750 // 最大高度限制
	}

	prefillIndex := -1
	prefillCustom := ""
	if previous != nil {
		if previous.SelectedIndex != nil {
			prefillIndex = *previous.SelectedIndex
		}
		if strings.TrimSpace(previous.AdditionalInput) != "" {
			prefillCustom = strings.TrimSpace(previous.AdditionalInput)
		}
	}
	safePrefillCustom := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(prefillCustom, "'", "''"), "\r", " "), "\n", " ")

	// 构建PowerShell脚本
	script := fmt.Sprintf(`
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$form = New-Object System.Windows.Forms.Form
$form.Text = 'AI 需要你的选择'
$form.ClientSize = New-Object System.Drawing.Size(500,%d)
$form.StartPosition = 'CenterScreen'
$form.TopMost = $true
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)

# 问题标签
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,20)
$label.Size = New-Object System.Drawing.Size(450,60)
$label.Text = '%s'
$label.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',11,[System.Drawing.FontStyle]::Bold)
$label.AutoSize = $false
$form.Controls.Add($label)

# 分隔线
$separator = New-Object System.Windows.Forms.Label
$separator.Location = New-Object System.Drawing.Point(20,85)
$separator.Size = New-Object System.Drawing.Size(450,2)
$separator.BorderStyle = 'Fixed3D'
$form.Controls.Add($separator)

# 提示标签
$hint = New-Object System.Windows.Forms.Label
$hint.Location = New-Object System.Drawing.Point(20,95)
$hint.Size = New-Object System.Drawing.Size(450,25)
$hint.Text = '请选择一个选项：'
$hint.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',9)
$hint.ForeColor = [System.Drawing.Color]::Gray
$form.Controls.Add($hint)

# 单选按钮组
$radioButtons = @()
$script:selectedIndex = -1
`, clientHeight, strings.ReplaceAll(q.Question, "'", "''"))

	// 添加单选按钮
	for i, opt := range q.Options {
		yPos := 125 + i*optionHeight
		script += fmt.Sprintf(`
$radio%d = New-Object System.Windows.Forms.RadioButton
$radio%d.Location = New-Object System.Drawing.Point(30,%d)
$radio%d.Size = New-Object System.Drawing.Size(440,25)
$radio%d.Text = '%s'
$radio%d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$radio%d.Add_Click({
    $script:selectedIndex = %d
    $customInput.Enabled = $false
    $customInput.BackColor = [System.Drawing.Color]::WhiteSmoke
})
$form.Controls.Add($radio%d)
$radioButtons += $radio%d
`, i, i, yPos, i, i, strings.ReplaceAll(opt, "'", "''"), i, i, i, i, i)
	}

	// 添加"其他"选项
	otherYPos := 125 + len(q.Options)*optionHeight
	script += fmt.Sprintf(`
# 其他选项
$radioOther = New-Object System.Windows.Forms.RadioButton
$radioOther.Location = New-Object System.Drawing.Point(30,%d)
$radioOther.Size = New-Object System.Drawing.Size(100,25)
$radioOther.Text = '其他：'
$radioOther.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$radioOther.Add_Click({
    $script:selectedIndex = -1
    $customInput.Enabled = $true
    $customInput.BackColor = [System.Drawing.Color]::White
    $customInput.Focus()
})
$form.Controls.Add($radioOther)
$radioButtons += $radioOther

# 自定义输入框
$customInput = New-Object System.Windows.Forms.TextBox
$customInput.Location = New-Object System.Drawing.Point(140,%d)
$customInput.Size = New-Object System.Drawing.Size(330,25)
$customInput.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$customInput.Enabled = $false
$customInput.BackColor = [System.Drawing.Color]::WhiteSmoke
$customInput.Add_Click({
    $radioOther.Checked = $true
    $script:selectedIndex = -1
})
$form.Controls.Add($customInput)
`, otherYPos, otherYPos+2)

	// 根据既有答案或默认值初始化选中项
	script += fmt.Sprintf(`
$prefillIndex = %[1]d
$prefillCustom = '%[2]s'
if ($prefillIndex -ge 0 -and $prefillIndex -lt $radioButtons.Count) {
    $radioButtons[$prefillIndex].Checked = $true
    $script:selectedIndex = $prefillIndex
} elseif ($prefillCustom -ne '') {
    $radioOther.Checked = $true
    $customInput.Enabled = $true
    $customInput.BackColor = [System.Drawing.Color]::White
    $customInput.Text = '%[2]s'
    $customInput.SelectionStart = $customInput.Text.Length
    $customInput.SelectionLength = 0
    $script:selectedIndex = -1
} elseif ($radioButtons.Count -gt 0) {
    $radioButtons[0].Checked = $true
    $script:selectedIndex = 0
}
`, prefillIndex, safePrefillCustom)
	script += fmt.Sprintf(`
# 按钮面板
$buttonPanel = New-Object System.Windows.Forms.Panel
$buttonPanel.Dock = [System.Windows.Forms.DockStyle]::Bottom
$buttonPanel.Height = %d
$buttonPanel.BackColor = [System.Drawing.Color]::WhiteSmoke
$form.Controls.Add($buttonPanel)

$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(280,20)
$okButton.Size = New-Object System.Drawing.Size(90,30)
$okButton.Text = '确定'
$okButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$okButton.BackColor = [System.Drawing.Color]::FromArgb(0,120,215)
$okButton.ForeColor = [System.Drawing.Color]::White
$okButton.FlatStyle = 'Flat'
$okButton.FlatAppearance.BorderSize = 0
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$form.AcceptButton = $okButton
$buttonPanel.Controls.Add($okButton)

$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(380,20)
$cancelButton.Size = New-Object System.Drawing.Size(90,30)
$cancelButton.Text = '取消'
$cancelButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$cancelButton.FlatStyle = 'Flat'
$cancelButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $cancelButton
$buttonPanel.Controls.Add($cancelButton)

$result = $form.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
    if ($script:selectedIndex -eq -1) {
        # 选择了"其他"选项
        Write-Output "CUSTOM|$($customInput.Text)"
    } elseif ($script:selectedIndex -ge 0) {
        Write-Output $script:selectedIndex
    } else {
        Write-Output "CANCELLED"
    }
} else {
    Write-Output "CANCELLED"
}
`, buttonPanelHeight)

	result, err := runPowerShellScript(script)
	if err != nil {
		return tools.Answer{}, false, err
	}
	if result == "CANCELLED" {
		return tools.Answer{}, true, nil
	}

	// 检查是否是自定义输入
	if strings.HasPrefix(result, "CUSTOM|") {
		customText := strings.TrimPrefix(result, "CUSTOM|")
		return tools.Answer{
			ID:              q.ID,
			Type:            q.Type,
			AdditionalInput: customText,
		}, false, nil
	}

	var idx int
	fmt.Sscanf(result, "%d", &idx)

	return tools.Answer{
		ID:            q.ID,
		Type:          q.Type,
		SelectedIndex: &idx,
	}, false, nil
}

// showMultipleChoice 显示多选对话框（优化版：使用CheckBox）
func (m *NativeManager) showMultipleChoice(q tools.Question, previous *tools.Answer) (tools.Answer, bool, error) {
	// 计算窗口高度：基础高度 + 每个选项的高度 + "其他"选项高度 + 按钮面板高度
	optionHeight := 35
	baseHeight := 220
	buttonPanelHeight := 70
	otherOptionHeight := 40 // "其他"选项 + 输入框的高度
	clientHeight := baseHeight + len(q.Options)*optionHeight + otherOptionHeight + buttonPanelHeight
	if clientHeight > 760 {
		clientHeight = 760 // 最大高度限制
	}

	selectedSeed := ""
	if previous != nil {
		valid := make([]string, 0, len(previous.SelectedIndices))
		for _, idx := range previous.SelectedIndices {
			if idx >= 0 && idx < len(q.Options) {
				valid = append(valid, fmt.Sprintf("%d", idx))
			}
		}
		selectedSeed = strings.Join(valid, ",")
	}

	customPrefill := ""
	if previous != nil && strings.TrimSpace(previous.AdditionalInput) != "" {
		customPrefill = strings.TrimSpace(previous.AdditionalInput)
	}
	safeCustomPrefill := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(customPrefill, "'", "''"), "\r", " "), "\n", " ")

	script := fmt.Sprintf(`
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$form = New-Object System.Windows.Forms.Form
$form.Text = 'AI 需要你的选择（可多选）'
$form.ClientSize = New-Object System.Drawing.Size(500,%d)
$form.StartPosition = 'CenterScreen'
$form.TopMost = $true
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)

# 问题标签
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,20)
$label.Size = New-Object System.Drawing.Size(450,60)
$label.Text = '%s'
$label.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',11,[System.Drawing.FontStyle]::Bold)
$label.AutoSize = $false
$form.Controls.Add($label)

# 分隔线
$separator = New-Object System.Windows.Forms.Label
$separator.Location = New-Object System.Drawing.Point(20,85)
$separator.Size = New-Object System.Drawing.Size(450,2)
$separator.BorderStyle = 'Fixed3D'
$form.Controls.Add($separator)

# 提示标签
$hint = New-Object System.Windows.Forms.Label
$hint.Location = New-Object System.Drawing.Point(20,95)
$hint.Size = New-Object System.Drawing.Size(450,25)
$hint.Text = '请选择一个或多个选项（可多选）：'
$hint.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',9)
$hint.ForeColor = [System.Drawing.Color]::FromArgb(0,120,215)
$form.Controls.Add($hint)

# 复选框组
$checkBoxes = @()
`, clientHeight, strings.ReplaceAll(q.Question, "'", "''"))

	// 添加复选框
	for i, opt := range q.Options {
		yPos := 130 + i*optionHeight
		script += fmt.Sprintf(`
$check%d = New-Object System.Windows.Forms.CheckBox
$check%d.Location = New-Object System.Drawing.Point(30,%d)
$check%d.Size = New-Object System.Drawing.Size(440,28)
$check%d.Text = '%s'
$check%d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$check%d.Cursor = [System.Windows.Forms.Cursors]::Hand
$check%d.Add_CheckedChanged({
    if ($checkOther.Checked) {
        $customInput.Enabled = $true
        $customInput.BackColor = [System.Drawing.Color]::White
    }
})
$form.Controls.Add($check%d)
$checkBoxes += $check%d
`, i, i, yPos, i, i, strings.ReplaceAll(opt, "'", "''"), i, i, i, i, i)
	}

	// 添加"其他"选项
	otherYPos := 130 + len(q.Options)*optionHeight
	script += fmt.Sprintf(`
# 其他选项
$checkOther = New-Object System.Windows.Forms.CheckBox
$checkOther.Location = New-Object System.Drawing.Point(30,%d)
$checkOther.Size = New-Object System.Drawing.Size(100,28)
$checkOther.Text = '其他：'
$checkOther.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$checkOther.Cursor = [System.Windows.Forms.Cursors]::Hand
$checkOther.Add_CheckedChanged({
    if ($checkOther.Checked) {
        $customInput.Enabled = $true
        $customInput.BackColor = [System.Drawing.Color]::White
        $customInput.Focus()
    } else {
        $customInput.Enabled = $false
        $customInput.BackColor = [System.Drawing.Color]::WhiteSmoke
    }
})
$form.Controls.Add($checkOther)
$checkBoxes += $checkOther

# 自定义输入框
$customInput = New-Object System.Windows.Forms.TextBox
$customInput.Location = New-Object System.Drawing.Point(140,%d)
$customInput.Size = New-Object System.Drawing.Size(330,25)
$customInput.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$customInput.Enabled = $false
$customInput.BackColor = [System.Drawing.Color]::WhiteSmoke
$customInput.Add_Click({
    $checkOther.Checked = $true
})
$form.Controls.Add($customInput)
`, otherYPos, otherYPos+2)

	script += fmt.Sprintf(`
$prefillIndices = '%s'
$prefillCustom = '%s'
if ($prefillIndices -ne '') {
    foreach ($token in $prefillIndices.Split(',')) {
        if ($token -ne '') {
            $prefIdx = [int]$token
            if ($prefIdx -ge 0 -and $prefIdx -lt ($checkBoxes.Count - 1)) {
                $checkBoxes[$prefIdx].Checked = $true
            }
        }
    }
}
if ($prefillCustom -ne '') {
    $checkOther.Checked = $true
    $customInput.Enabled = $true
    $customInput.BackColor = [System.Drawing.Color]::White
    $customInput.Text = '%s'
    $customInput.SelectionStart = $customInput.Text.Length
    $customInput.SelectionLength = 0
}
`, selectedSeed, safeCustomPrefill, safeCustomPrefill)

	script += fmt.Sprintf(`
# 按钮面板
$buttonPanel = New-Object System.Windows.Forms.Panel
$buttonPanel.Dock = [System.Windows.Forms.DockStyle]::Bottom
$buttonPanel.Height = %d
$buttonPanel.BackColor = [System.Drawing.Color]::WhiteSmoke
$form.Controls.Add($buttonPanel)

# 选中计数标签
$countLabel = New-Object System.Windows.Forms.Label
$countLabel.Location = New-Object System.Drawing.Point(20,20)
$countLabel.Size = New-Object System.Drawing.Size(200,25)
$countLabel.Text = '已选择: 0 项'
$countLabel.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',9)
$countLabel.ForeColor = [System.Drawing.Color]::Gray
$buttonPanel.Controls.Add($countLabel)

# 更新计数
$updateCount = {
    $count = 0
    foreach ($cb in $checkBoxes) {
        if ($cb.Checked) { $count++ }
    }
    $countLabel.Text = "已选择: $count 项"
}

foreach ($cb in $checkBoxes) {
    $cb.Add_CheckedChanged($updateCount)
}

$updateCount.Invoke()

$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(280,20)
$okButton.Size = New-Object System.Drawing.Size(90,30)
$okButton.Text = '确定'
$okButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$okButton.BackColor = [System.Drawing.Color]::FromArgb(0,120,215)
$okButton.ForeColor = [System.Drawing.Color]::White
$okButton.FlatStyle = 'Flat'
$okButton.FlatAppearance.BorderSize = 0
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$form.AcceptButton = $okButton
$buttonPanel.Controls.Add($okButton)

$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(380,20)
$cancelButton.Size = New-Object System.Drawing.Size(90,30)
$cancelButton.Text = '取消'
$cancelButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$cancelButton.FlatStyle = 'Flat'
$cancelButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $cancelButton
$buttonPanel.Controls.Add($cancelButton)

$result = $form.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
    $indices = @()
    $customText = ""
    
    # 检查常规选项（不包括最后一个"其他"选项）
    for ($i = 0; $i -lt ($checkBoxes.Count - 1); $i++) {
        if ($checkBoxes[$i].Checked) {
            $indices += $i
        }
    }
    
    # 检查"其他"选项
    if ($checkOther.Checked -and $customInput.Text -ne "") {
        $customText = $customInput.Text
    }
    
    # 输出结果
    if ($indices.Count -gt 0 -or $customText -ne "") {
        $output = ($indices -join ',')
        if ($customText -ne "") {
            if ($output -ne "") {
                $output += "|CUSTOM|$customText"
            } else {
                $output = "CUSTOM|$customText"
            }
        }
        Write-Output $output
    } else {
        Write-Output "NONE"
    }
} else {
    Write-Output "CANCELLED"
}
`, buttonPanelHeight)

	result, err := runPowerShellScript(script)
	if err != nil {
		return tools.Answer{}, false, err
	}
	if result == "CANCELLED" {
		return tools.Answer{}, true, nil
	}
	if result == "NONE" {
		// 允许不选择任何选项
		return tools.Answer{
			ID:              q.ID,
			Type:            q.Type,
			SelectedIndices: []int{},
		}, false, nil
	}

	// 解析结果
	indices := []int{}
	customText := ""

	// 检查是否包含自定义输入
	if strings.Contains(result, "|CUSTOM|") {
		parts := strings.Split(result, "|CUSTOM|")
		if parts[0] != "" && parts[0] != "CUSTOM" {
			// 有常规选项
			for _, s := range strings.Split(parts[0], ",") {
				var idx int
				fmt.Sscanf(s, "%d", &idx)
				indices = append(indices, idx)
			}
		}
		if len(parts) > 1 {
			customText = parts[1]
		}
	} else {
		// 只有常规选项
		for _, s := range strings.Split(result, ",") {
			var idx int
			fmt.Sscanf(s, "%d", &idx)
			indices = append(indices, idx)
		}
	}

	return tools.Answer{
		ID:              q.ID,
		Type:            q.Type,
		SelectedIndices: indices,
		AdditionalInput: customText,
	}, false, nil
}

// showFreeText 显示文本输入对话框（优化版）
func (m *NativeManager) showFreeText(q tools.Question, previous *tools.Answer) (tools.Answer, bool, error) {
	placeholder := q.Placeholder
	if placeholder == "" {
		placeholder = "请在这里输入你的回答..."
	}

	clientHeight := 360
	buttonPanelHeight := 60

	prefillText := ""
	if previous != nil {
		if text := previous.Text; strings.TrimSpace(text) != "" {
			prefillText = text
		}
	}
	prefillEncoded := ""
	if prefillText != "" {
		prefillEncoded = base64.StdEncoding.EncodeToString([]byte(prefillText))
	}

	script := fmt.Sprintf(`
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$form = New-Object System.Windows.Forms.Form
$form.Text = 'AI 需要你的回答'
$form.ClientSize = New-Object System.Drawing.Size(550,%d)
$form.StartPosition = 'CenterScreen'
$form.TopMost = $true
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)

# 问题标签
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,20)
$label.Size = New-Object System.Drawing.Size(500,60)
$label.Text = '%s'
$label.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',11,[System.Drawing.FontStyle]::Bold)
$label.AutoSize = $false
$form.Controls.Add($label)

# 分隔线
$separator = New-Object System.Windows.Forms.Label
$separator.Location = New-Object System.Drawing.Point(20,85)
$separator.Size = New-Object System.Drawing.Size(500,2)
$separator.BorderStyle = 'Fixed3D'
$form.Controls.Add($separator)

# 提示标签
$hint = New-Object System.Windows.Forms.Label
$hint.Location = New-Object System.Drawing.Point(20,95)
$hint.Size = New-Object System.Drawing.Size(500,25)
$hint.Text = '请输入你的回答：'
$hint.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',9)
$hint.ForeColor = [System.Drawing.Color]::Gray
$form.Controls.Add($hint)

# 文本框
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(20,125)
$textBox.Size = New-Object System.Drawing.Size(500,150)
$textBox.Multiline = $true
$textBox.ScrollBars = 'Vertical'
$textBox.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$textBox.BorderStyle = 'FixedSingle'

$placeholder = '%s'
$textBox.Text = $placeholder
$textBox.ForeColor = [System.Drawing.Color]::Gray

$textBox.Add_GotFocus({
    if ($textBox.Text -eq $placeholder) {
        $textBox.Text = ''
        $textBox.ForeColor = [System.Drawing.Color]::Black
    }
})

$textBox.Add_LostFocus({
    if ($textBox.Text -eq '') {
        $textBox.Text = $placeholder
        $textBox.ForeColor = [System.Drawing.Color]::Gray
    }
})

$form.Controls.Add($textBox)

# 字符计数标签
$charCount = New-Object System.Windows.Forms.Label
$charCount.Location = New-Object System.Drawing.Point(20,280)
$charCount.Size = New-Object System.Drawing.Size(200,20)
$charCount.Text = '字符数: 0'
$charCount.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',8)
$charCount.ForeColor = [System.Drawing.Color]::Gray
$form.Controls.Add($charCount)

$textBox.Add_TextChanged({
    $len = if ($textBox.Text -eq $placeholder) { 0 } else { $textBox.Text.Length }
    $charCount.Text = "字符数: $len"
})

$prefillRaw = '%s'
if ($prefillRaw -ne '') {
    try {
        $prefillDec = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($prefillRaw))
        if ($prefillDec -ne '') {
            $textBox.Text = $prefillDec
            $textBox.ForeColor = [System.Drawing.Color]::Black
            $charCount.Text = "字符数: $($textBox.Text.Length)"
        }
    } catch { }
}

# 按钮面板
$buttonPanel = New-Object System.Windows.Forms.Panel
$buttonPanel.Dock = [System.Windows.Forms.DockStyle]::Bottom
$buttonPanel.Height = %d
$buttonPanel.BackColor = [System.Drawing.Color]::WhiteSmoke
$form.Controls.Add($buttonPanel)

$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(330,15)
$okButton.Size = New-Object System.Drawing.Size(90,30)
$okButton.Text = '确定'
$okButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$okButton.BackColor = [System.Drawing.Color]::FromArgb(0,120,215)
$okButton.ForeColor = [System.Drawing.Color]::White
$okButton.FlatStyle = 'Flat'
$okButton.FlatAppearance.BorderSize = 0
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$form.AcceptButton = $okButton
$buttonPanel.Controls.Add($okButton)

$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(430,15)
$cancelButton.Size = New-Object System.Drawing.Size(90,30)
$cancelButton.Text = '取消'
$cancelButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$cancelButton.FlatStyle = 'Flat'
$cancelButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $cancelButton
$buttonPanel.Controls.Add($cancelButton)

$result = $form.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
    $text = if ($textBox.Text -eq $placeholder) { '' } else { $textBox.Text }
    Write-Output $text
} else {
    Write-Output "CANCELLED"
}
`, clientHeight, strings.ReplaceAll(q.Question, "'", "''"), strings.ReplaceAll(placeholder, "'", "''"), prefillEncoded, buttonPanelHeight)

	result, err := runPowerShellScript(script)
	if err != nil {
		return tools.Answer{}, false, err
	}
	if result == "CANCELLED" {
		return tools.Answer{}, true, nil
	}

	return tools.Answer{
		ID:   q.ID,
		Type: q.Type,
		Text: result,
	}, false, nil
}

// showMultipleQuestions 显示多个问题（标签页模式）
func (m *NativeManager) showMultipleQuestions(questions []tools.Question, timeout time.Duration, previous []tools.Answer) ([]tools.Answer, bool, error) {
	// 构建 PowerShell 脚本，创建带标签页的窗口
	script := `
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$form = New-Object System.Windows.Forms.Form
$form.Text = 'AI 问题澄清 (共 ` + fmt.Sprintf("%d", len(questions)) + ` 题)'
$form.ClientSize = New-Object System.Drawing.Size(700,600)
$form.StartPosition = 'CenterScreen'
$form.TopMost = $true
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)

# 创建标签页控件
$tabControl = New-Object System.Windows.Forms.TabControl
$tabControl.Location = New-Object System.Drawing.Point(10,10)
$tabControl.Size = New-Object System.Drawing.Size(670,480)
$tabControl.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$form.Controls.Add($tabControl)

# 存储答案的哈希表
$answers = @{}
`

	// 为每个问题创建标签页
	for i, q := range questions {
		var prefill *tools.Answer
		if i < len(previous) {
			prefill = &previous[i]
		}
		script += m.generateTabPage(i, q, prefill)
	}

	// 添加底部控制栏
	script += `
# 提示标签
$hintLabel = New-Object System.Windows.Forms.Label
$hintLabel.Location = New-Object System.Drawing.Point(20,500)
$hintLabel.Size = New-Object System.Drawing.Size(660,20)
$hintLabel.Text = '💡 提示：可以随时切换标签页修改答案，最后统一提交'
$hintLabel.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',9,[System.Drawing.FontStyle]::Italic)
$hintLabel.ForeColor = [System.Drawing.Color]::Gray
$form.Controls.Add($hintLabel)

# 按钮面板
$buttonPanel = New-Object System.Windows.Forms.Panel
$buttonPanel.Location = New-Object System.Drawing.Point(10,530)
$buttonPanel.Size = New-Object System.Drawing.Size(670,60)
$buttonPanel.BackColor = [System.Drawing.Color]::WhiteSmoke
$form.Controls.Add($buttonPanel)

# 提交按钮
$submitButton = New-Object System.Windows.Forms.Button
$submitButton.Location = New-Object System.Drawing.Point(450,15)
$submitButton.Size = New-Object System.Drawing.Size(100,30)
$submitButton.Text = '提交所有答案'
$submitButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$submitButton.BackColor = [System.Drawing.Color]::FromArgb(0,120,215)
$submitButton.ForeColor = [System.Drawing.Color]::White
$submitButton.FlatStyle = 'Flat'
$submitButton.FlatAppearance.BorderSize = 0
$submitButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$submitButton.Add_Click({
    # 收集所有答案
    ` + m.generateAnswerCollectionInline(questions) + `
    
    $form.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $form.Close()
})
$buttonPanel.Controls.Add($submitButton)

# 取消按钮
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(560,15)
$cancelButton.Size = New-Object System.Drawing.Size(90,30)
$cancelButton.Text = '取消'
$cancelButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$cancelButton.FlatStyle = 'Flat'
$cancelButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$cancelButton.Add_Click({
    $form.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $form.Close()
})
$buttonPanel.Controls.Add($cancelButton)

$result = $form.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
    # 输出所有答案
    for ($i = 0; $i -lt ` + fmt.Sprintf("%d", len(questions)) + `; $i++) {
        Write-Output $answers[$i]
    }
} else {
    Write-Output "CANCELLED"
}
`

	result, err := runPowerShellScript(script)
	if err != nil {
		return nil, false, err
	}
	if result == "CANCELLED" {
		return nil, true, nil
	}

	// 解析答案
	lines := strings.Split(result, "\n")
	answers := make([]tools.Answer, len(questions))

	for i, line := range lines {
		if i >= len(questions) {
			break
		}

		line = strings.TrimSpace(line)
		q := questions[i]

		switch q.Type {
		case "single":
			if strings.HasPrefix(line, "CUSTOM|") {
				customText := strings.TrimPrefix(line, "CUSTOM|")
				answers[i] = tools.Answer{
					ID:              q.ID,
					Type:            q.Type,
					AdditionalInput: customText,
				}
			} else {
				var idx int
				fmt.Sscanf(line, "%d", &idx)
				answers[i] = tools.Answer{
					ID:            q.ID,
					Type:          q.Type,
					SelectedIndex: &idx,
				}
			}

		case "multiple":
			indices := []int{}
			customText := ""

			if strings.Contains(line, "|CUSTOM|") {
				parts := strings.Split(line, "|CUSTOM|")
				if parts[0] != "" && parts[0] != "CUSTOM" {
					for _, s := range strings.Split(parts[0], ",") {
						var idx int
						fmt.Sscanf(s, "%d", &idx)
						indices = append(indices, idx)
					}
				}
				if len(parts) > 1 {
					customText = parts[1]
				}
			} else if line != "NONE" {
				for _, s := range strings.Split(line, ",") {
					var idx int
					fmt.Sscanf(s, "%d", &idx)
					indices = append(indices, idx)
				}
			}

			answers[i] = tools.Answer{
				ID:              q.ID,
				Type:            q.Type,
				SelectedIndices: indices,
				AdditionalInput: customText,
			}

		case "free_text":
			answers[i] = tools.Answer{
				ID:   q.ID,
				Type: q.Type,
				Text: line,
			}
		}
	}

	return answers, false, nil
}

// generateTabPage 生成单个标签页的 PowerShell 代码
func (m *NativeManager) generateTabPage(index int, q tools.Question, prefill *tools.Answer) string {
	script := fmt.Sprintf(`
# 标签页 %d
$tab%d = New-Object System.Windows.Forms.TabPage
$tab%d.Text = '问题 %d'
$tab%d.BackColor = [System.Drawing.Color]::White
$tabControl.Controls.Add($tab%d)

# 问题标题
$label%d = New-Object System.Windows.Forms.Label
$label%d.Location = New-Object System.Drawing.Point(20,20)
$label%d.Size = New-Object System.Drawing.Size(620,60)
$label%d.Text = '%s'
$label%d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',11,[System.Drawing.FontStyle]::Bold)
$label%d.AutoSize = $false
$tab%d.Controls.Add($label%d)

# 分隔线
$sep%d = New-Object System.Windows.Forms.Label
$sep%d.Location = New-Object System.Drawing.Point(20,85)
$sep%d.Size = New-Object System.Drawing.Size(620,2)
$sep%d.BorderStyle = 'Fixed3D'
$tab%d.Controls.Add($sep%d)
`, index, index, index, index+1, index, index,
		index, index, index, index, strings.ReplaceAll(q.Question, "'", "''"), index, index, index, index,
		index, index, index, index, index, index)

	switch q.Type {
	case "single":
		script += m.generateSingleChoiceTab(index, q, prefill)
	case "multiple":
		script += m.generateMultipleChoiceTab(index, q, prefill)
	case "free_text":
		script += m.generateFreeTextTab(index, q, prefill)
	}

	return script
}

// generateSingleChoiceTab 生成单选题标签页
func (m *NativeManager) generateSingleChoiceTab(index int, q tools.Question, prefill *tools.Answer) string {
	prefillIndex := -1
	prefillCustom := ""
	if prefill != nil {
		if prefill.SelectedIndex != nil {
			prefillIndex = *prefill.SelectedIndex
		}
		if strings.TrimSpace(prefill.AdditionalInput) != "" {
			prefillCustom = strings.TrimSpace(prefill.AdditionalInput)
		}
	}
	safePrefillCustom := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(prefillCustom, "'", "''"), "\r", " "), "\n", " ")

	script := fmt.Sprintf(`
# 单选题选项（滚动容器）
$radioGroup%d = @()
$panel%d = New-Object System.Windows.Forms.Panel
$panel%d.Location = New-Object System.Drawing.Point(20,110)
$panel%d.Size = New-Object System.Drawing.Size(620,300)
$panel%d.AutoScroll = $true
$panel%d.BackColor = [System.Drawing.Color]::White
$tab%d.Controls.Add($panel%d)
`, index, index, index, index, index, index, index, index)

	for i, opt := range q.Options {
		safeOpt := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(opt, "'", "''"), "\r", " "), "\n", " ")
		yPos := 10 + i*28
		script += fmt.Sprintf(`
$radio%[1]d_%[2]d = New-Object System.Windows.Forms.RadioButton
$radio%[1]d_%[2]d.Location = New-Object System.Drawing.Point(10,%[3]d)
$radio%[1]d_%[2]d.Size = New-Object System.Drawing.Size(580,23)
$radio%[1]d_%[2]d.Text = '%[4]s'
$radio%[1]d_%[2]d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$radio%[1]d_%[2]d.Add_Click({
    $answers[%[1]d] = '%[2]d'
    $customInput%[1]d.ReadOnly = $true
    $customInput%[1]d.Text = ''
    $customInput%[1]d.BackColor = [System.Drawing.Color]::WhiteSmoke
})
$panel%[1]d.Controls.Add($radio%[1]d_%[2]d)
$radioGroup%[1]d += $radio%[1]d_%[2]d
`, index, i, yPos, safeOpt)
	}

	// 添加"其他"选项与输入框
	otherYPos := 10 + len(q.Options)*28
	script += fmt.Sprintf(`
# 自定义输入框（与"其他"同一行）
$customInput%[1]d = New-Object System.Windows.Forms.TextBox
$customInput%[1]d.Location = New-Object System.Drawing.Point(120,%[2]d)
$customInput%[1]d.Size = New-Object System.Drawing.Size(450,23)
$customInput%[1]d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$customInput%[1]d.ReadOnly = $true
$customInput%[1]d.BackColor = [System.Drawing.Color]::WhiteSmoke
$panel%[1]d.Controls.Add($customInput%[1]d)

# 其他选项
$radioOther%[1]d = New-Object System.Windows.Forms.RadioButton
$radioOther%[1]d.Location = New-Object System.Drawing.Point(10,%[2]d)
$radioOther%[1]d.Size = New-Object System.Drawing.Size(100,23)
$radioOther%[1]d.Text = '其他：'
$radioOther%[1]d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$radioOther%[1]d.Add_Click({
    $customInput%[1]d.ReadOnly = $false
    $customInput%[1]d.BackColor = [System.Drawing.Color]::White
    $customInput%[1]d.Focus()
})
$panel%[1]d.Controls.Add($radioOther%[1]d)
$radioGroup%[1]d += $radioOther%[1]d

$customInput%[1]d.Add_Enter({
    $radioOther%[1]d.Checked = $true
})
$customInput%[1]d.Add_TextChanged({
    if ($radioOther%[1]d.Checked) {
        $answers[%[1]d] = "CUSTOM|$($customInput%[1]d.Text)"
    }
})
`, index, otherYPos)

	script += fmt.Sprintf(`
$prefillIndex = %[1]d
$prefillCustom = '%[2]s'
if ($prefillIndex -ge 0 -and $prefillIndex -lt $radioGroup%[3]d.Count) {
    $radioGroup%[3]d[$prefillIndex].Checked = $true
    $answers[%[3]d] = "$prefillIndex"
} elseif ($prefillCustom -ne '') {
    $radioOther%[3]d.Checked = $true
    $customInput%[3]d.ReadOnly = $false
    $customInput%[3]d.BackColor = [System.Drawing.Color]::White
    $customInput%[3]d.Text = '%[2]s'
    $customInput%[3]d.SelectionStart = $customInput%[3]d.Text.Length
    $customInput%[3]d.SelectionLength = 0
    $answers[%[3]d] = "CUSTOM|$($customInput%[3]d.Text)"
} elseif ($radioGroup%[3]d.Count -gt 0) {
    $radioGroup%[3]d[0].Checked = $true
    $answers[%[3]d] = "0"
}
`, prefillIndex, safePrefillCustom, index)

	return script
}

// generateMultipleChoiceTab 生成多选题标签页
func (m *NativeManager) generateMultipleChoiceTab(index int, q tools.Question, prefill *tools.Answer) string {
	selectedSeed := ""
	if prefill != nil && len(prefill.SelectedIndices) > 0 {
		valid := make([]string, 0, len(prefill.SelectedIndices))
		for _, idx := range prefill.SelectedIndices {
			if idx >= 0 && idx < len(q.Options) {
				valid = append(valid, fmt.Sprintf("%d", idx))
			}
		}
		selectedSeed = strings.Join(valid, ",")
	}

	customPrefill := ""
	if prefill != nil && strings.TrimSpace(prefill.AdditionalInput) != "" {
		customPrefill = strings.TrimSpace(prefill.AdditionalInput)
	}
	safeCustomPrefill := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(customPrefill, "'", "''"), "\r", " "), "\n", " ")

	script := fmt.Sprintf(`
# 多选题选项
$checkBoxes%d = @()

# 滚动容器，避免控件被遮挡或超出可视区域
$panel%d = New-Object System.Windows.Forms.Panel
$panel%d.Location = New-Object System.Drawing.Point(20,110)
$panel%d.Size = New-Object System.Drawing.Size(620,300)
$panel%d.AutoScroll = $true
$panel%d.BackColor = [System.Drawing.Color]::White
$tab%d.Controls.Add($panel%d)
`, index, index, index, index, index, index, index, index)

	// 添加所有选项的复选框（放入滚动容器中）
	for i, opt := range q.Options {
		safeOpt := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(opt, "'", "''"), "\r", " "), "\n", " ")
		yPos := 10 + i*30
		script += fmt.Sprintf(`
$check%[1]d_%[2]d = New-Object System.Windows.Forms.CheckBox
$check%[1]d_%[2]d.Location = New-Object System.Drawing.Point(10,%[3]d)
$check%[1]d_%[2]d.Size = New-Object System.Drawing.Size(580,25)
$check%[1]d_%[2]d.Text = '%[4]s'
$check%[1]d_%[2]d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$panel%[1]d.Controls.Add($check%[1]d_%[2]d)
$checkBoxes%[1]d += $check%[1]d_%[2]d
`, index, i, yPos, safeOpt)
	}

	// 添加"其他"选项与自定义输入框（同样放入滚动容器）
	otherYPos := 10 + len(q.Options)*30
	script += fmt.Sprintf(`
# 自定义输入框（与"其他"同行）
$customInput%[1]d = New-Object System.Windows.Forms.TextBox
$customInput%[1]d.Location = New-Object System.Drawing.Point(120,%[2]d)
$customInput%[1]d.Size = New-Object System.Drawing.Size(450,23)
$customInput%[1]d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$customInput%[1]d.ReadOnly = $true
$customInput%[1]d.BackColor = [System.Drawing.Color]::WhiteSmoke
$panel%[1]d.Controls.Add($customInput%[1]d)

# 其他选项
$checkOther%[1]d = New-Object System.Windows.Forms.CheckBox
$checkOther%[1]d.Location = New-Object System.Drawing.Point(10,%[2]d)
$checkOther%[1]d.Size = New-Object System.Drawing.Size(100,25)
$checkOther%[1]d.Text = '其他：'
$checkOther%[1]d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$checkOther%[1]d.Add_CheckedChanged({
    if ($checkOther%[1]d.Checked) {
        $customInput%[1]d.ReadOnly = $false
        $customInput%[1]d.BackColor = [System.Drawing.Color]::White
        $customInput%[1]d.Focus()
    } else {
        $customInput%[1]d.ReadOnly = $true
        $customInput%[1]d.Text = ''
        $customInput%[1]d.BackColor = [System.Drawing.Color]::WhiteSmoke
    }
})
$panel%[1]d.Controls.Add($checkOther%[1]d)
$checkBoxes%[1]d += $checkOther%[1]d

$customInput%[1]d.Add_Enter({
    $checkOther%[1]d.Checked = $true
})

# 初始化答案为 NONE
$answers[%[1]d] = 'NONE'
`, index, otherYPos)

	script += fmt.Sprintf(`
$prefillIndices = '%[1]s'
if ($prefillIndices -ne '') {
    foreach ($token in $prefillIndices.Split(',')) {
        if ($token -ne '') {
            $prefIdx = [int]$token
            if ($prefIdx -ge 0 -and $prefIdx -lt ($checkBoxes%[2]d.Count - 1)) {
                $checkBoxes%[2]d[$prefIdx].Checked = $true
            }
        }
    }
}
$prefillCustom = '%[3]s'
if ($prefillCustom -ne '') {
    $checkOther%[2]d.Checked = $true
    $customInput%[2]d.ReadOnly = $false
    $customInput%[2]d.BackColor = [System.Drawing.Color]::White
    $customInput%[2]d.Text = '%[3]s'
    $customInput%[2]d.SelectionStart = $customInput%[2]d.Text.Length
    $customInput%[2]d.SelectionLength = 0
}
`, selectedSeed, index, safeCustomPrefill)

	return script
}

// generateFreeTextTab 生成简答题标签页
func (m *NativeManager) generateFreeTextTab(index int, q tools.Question, prefill *tools.Answer) string {
	placeholder := q.Placeholder
	if placeholder == "" {
		placeholder = "请在这里输入你的回答..."
	}

	prefillText := ""
	if prefill != nil {
		if text := prefill.Text; strings.TrimSpace(text) != "" {
			prefillText = text
		}
	}
	prefillEncoded := ""
	if prefillText != "" {
		prefillEncoded = base64.StdEncoding.EncodeToString([]byte(prefillText))
	}

	return fmt.Sprintf(`
# 简答题输入框
$textBox%d = New-Object System.Windows.Forms.TextBox
$textBox%d.Location = New-Object System.Drawing.Point(30,110)
$textBox%d.Size = New-Object System.Drawing.Size(600,250)
$textBox%d.Multiline = $true
$textBox%d.ScrollBars = 'Vertical'
$textBox%d.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$textBox%d.BorderStyle = 'FixedSingle'
$textBox%d.Text = '%s'
$textBox%d.ForeColor = [System.Drawing.Color]::Gray

$textBox%d.Add_GotFocus({
    if ($textBox%d.Text -eq '%s') {
        $textBox%d.Text = ''
        $textBox%d.ForeColor = [System.Drawing.Color]::Black
    }
})

$textBox%d.Add_TextChanged({
    $text = if ($textBox%d.Text -eq '%s') { '' } else { $textBox%d.Text }
    $answers[%d] = $text
})

$prefillRaw = '%s'
if ($prefillRaw -ne '') {
    try {
        $prefillDec = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($prefillRaw))
        if ($prefillDec -ne '') {
            $textBox%d.Text = $prefillDec
            $textBox%d.ForeColor = [System.Drawing.Color]::Black
            $answers[%d] = $prefillDec
        }
    } catch { }
}

$tab%d.Controls.Add($textBox%d)
`, index, index, index, index, index, index, index, index, strings.ReplaceAll(placeholder, "'", "''"), index,
		index, index, strings.ReplaceAll(placeholder, "'", "''"), index, index,
		index, index, strings.ReplaceAll(placeholder, "'", "''"), index, index,
		prefillEncoded, index, index, index, index, index)
}

func runPowerShellScript(script string) (string, error) {
	prefix := "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8;"
	fullScript := prefix + "\n" + script
	cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", fullScript)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("failed to show dialog: %w (output: %s)", err, string(output))
	}

	result := strings.TrimSpace(string(output))
	result = strings.TrimPrefix(result, "\ufeff")
	return result, nil
}

func (m *NativeManager) confirmAnswersNative(questions []tools.Question, answers []tools.Answer) (bool, error) {
	lines := make([]string, 0, len(questions)*3)
	for i, q := range questions {
		lines = append(lines, fmt.Sprintf("问题 %d：%s", i+1, q.Question))
		for _, line := range formatAnswerSummaryLines(q, answers[i]) {
			lines = append(lines, "  • "+line)
		}
		lines = append(lines, "")
	}

	summary := strings.Join(lines, "\r\n")
	encoded := base64.StdEncoding.EncodeToString([]byte(summary))

	script := fmt.Sprintf(`
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$summaryBytes = [Convert]::FromBase64String('%s')
$summary = [Text.Encoding]::UTF8.GetString($summaryBytes)

$form = New-Object System.Windows.Forms.Form
$form.Text = '确认提交'
$form.ClientSize = New-Object System.Drawing.Size(520,360)
$form.StartPosition = 'CenterScreen'
$form.TopMost = $true
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)

 $header = New-Object System.Windows.Forms.Label
 $header.Location = New-Object System.Drawing.Point(15,15)
 $header.Size = New-Object System.Drawing.Size(490,30)
 $header.Text = '请确认以下回答，如需调整请点击“返回修改”。'
 $header.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',9,[System.Drawing.FontStyle]::Regular)
 $header.ForeColor = [System.Drawing.Color]::FromArgb(64,64,64)
 $form.Controls.Add($header)

 $text = New-Object System.Windows.Forms.RichTextBox
 $text.Location = New-Object System.Drawing.Point(15,55)
 $text.Size = New-Object System.Drawing.Size(490,220)
 $text.Text = $summary
 $text.ReadOnly = $true
 $text.BackColor = [System.Drawing.SystemColors]::Window
 $text.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle
 $text.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
 $text.DetectUrls = $false
 $text.WordWrap = $true
 $text.ScrollBars = [System.Windows.Forms.RichTextBoxScrollBars]::Vertical
 $form.Controls.Add($text)
 $text.SelectionStart = 0
 $text.SelectionLength = 0

$confirmButton = New-Object System.Windows.Forms.Button
 $confirmButton.Location = New-Object System.Drawing.Point(300,295)
$confirmButton.Size = New-Object System.Drawing.Size(100,30)
$confirmButton.Text = '确认提交'
$confirmButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$confirmButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $confirmButton
$form.Controls.Add($confirmButton)

$cancelButton = New-Object System.Windows.Forms.Button
 $cancelButton.Location = New-Object System.Drawing.Point(410,295)
$cancelButton.Size = New-Object System.Drawing.Size(90,30)
$cancelButton.Text = '返回修改'
$cancelButton.Font = New-Object System.Drawing.Font('Microsoft YaHei UI',10)
$cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $cancelButton
$form.Controls.Add($cancelButton)

$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
    Write-Output 'CONFIRMED'
} else {
    Write-Output 'CANCELLED'
}
`, encoded)

	result, err := runPowerShellScript(script)
	if err != nil {
		return false, err
	}
	return result == "CONFIRMED", nil
}

// IsActive 检查是否有活动窗口
func (m *NativeManager) IsActive() bool {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.active
}

// generateAnswerCollectionInline 生成收集答案的 PowerShell 代码
func (m *NativeManager) generateAnswerCollectionInline(questions []tools.Question) string {
	script := ""
	for i, q := range questions {
		if q.Type == "multiple" {
			script += fmt.Sprintf(`
    # 收集问题 %d 的多选答案
    $indices = @()
    for ($j = 0; $j -lt ($checkBoxes%d.Count - 1); $j++) {
        if ($checkBoxes%d[$j].Checked) {
            $indices += $j
        }
    }
    $customText = ""
    if ($checkOther%d.Checked -and $customInput%d.Text -ne "") {
        $customText = $customInput%d.Text
    }
    if ($indices.Count -gt 0 -or $customText -ne "") {
        $output = ($indices -join ',')
        if ($customText -ne "") {
            if ($output -ne "") {
                $output += "|CUSTOM|$customText"
            } else {
                $output = "CUSTOM|$customText"
            }
        }
        $answers[%d] = $output
    } else {
        $answers[%d] = 'NONE'
    }
`, i+1, i, i, i, i, i, i, i)
		}
	}
	return script
}
